package com.neusoft.work.controller;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.neusoft.work.po.CurrentUserId;
import com.neusoft.work.service.CurrentUserIdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.work.po.PageResponseBean;
import com.neusoft.work.po.ResponseBean;
import com.neusoft.work.po.User;
import com.neusoft.work.service.RedisService;
import com.neusoft.work.service.UserService;
import com.neusoft.work.util.JWTTool;

@RequestMapping("/UserController")
@RestController
public class UserController {

	@Autowired
	private UserService us;
	@Autowired
	private RedisService rs;
	@Autowired
	private CurrentUserIdService cis;
	
	
	@PostMapping("/addUser")
	public ResponseBean<Integer> addUser(User user){
		return us.addUser(user);
	}
	
	@PostMapping("/updateUser")
	public ResponseBean<Integer> updateUser(User user){
		return us.updateUser(user);
	}
	
	@PostMapping("/deleteUser")
	public ResponseBean<Integer> deleteUser(Integer id){
		return us.deleteUser(id);
	}
	
	@PostMapping("/queryUserByName")
	public PageResponseBean<List<User>> queryUserByName(String realName,@RequestParam(required = false) Integer role,Long cur,Long number){
		return us.queryUserByName(realName,role,cur,number);
	}
	
	@PostMapping("/login")
	public ResponseBean<String> login(String userName,String password) throws JsonProcessingException{
		User data=new User();
		data.setPassword(password);
		data.setUserName(userName);
//		调用服务层
		ResponseBean<User> rb=us.getUser(data);
//		封装ReaponseBean
		ResponseBean<String> rb2=null;
		System.out.println(rb.getStatus());
		if(rb.getStatus()==200) {
//			得到登录者对象
			User user=rb.getData();
			CurrentUserId currentUserId=new CurrentUserId(1, user.getId());
			cis.setCurrentUserId(currentUserId);
//			把登录者转换为json
			ObjectMapper om=new ObjectMapper();
			String userJson=om.writeValueAsString(user);
			String token=JWTTool.createToken(userJson);
//			把令牌存入redis中
			rs.set(user.getId().toString(), token,50000,TimeUnit.SECONDS);
//			同时传递给前端一份
			rb2=new ResponseBean<>(token);
		}else {
			rb2=new ResponseBean<>(500,"fail");
			rb2.setMsg(rb.getMsg());
		}
		return rb2;
	}
}
